
#
# Streaming data object
#
class StreamingPacket
  buffer_view: null
  uid_buf: null
  sid_buf: null
  len_buf: null
  channel_buf: null
  HEADER_SIZE: (4 + 4 + 4 + 4)
  pcm_buff: null

  #
  # create empty buffer 
  #
  create_empty_packet:(pcm_buff_len, channel_count)->
    @buffer_view = new ArrayBuffer(@HEADER_SIZE + pcm_buff_len * 4 * channel_count)
    @map_header()
    @pcm_buff = new Float32Array(@buffer_view, @HEADER_SIZE, pcm_buff_len * channel_count)
    return

  #
  # map header buffer views 
  #
  map_header:->
    offset=0
    @uid_buf = new Uint32Array(@buffer_view, offset, 1)
    offset += 4
    @sid_buf = new Uint32Array(@buffer_view, offset, 1)
    offset += 4
    @len_buf = new Uint32Array(@buffer_view, offset, 1)
    offset += 4
    @channel_buf = new Uint32Array(@buffer_view, offset, 1)
    return

  #
  # returns data(ArrayBuffer) of packet
  #
  to_array_buffer:(uid, sid, pcm_data)->
    idx = 0
    @uid_buf[0] = uid
    @sid_buf[0] = sid
    @channel_buf[0] = pcm_data.length
    @len_buf[0] = pcm_data[0].length
    channel_count = @get_channel_count()
    for ch in [0...channel_count]
      for i in [0...pcm_data[0].length]
        @pcm_buff[idx] = pcm_data[ch][i]
        idx += 1

    return @buffer_view

  #
  # packet binary blob data to map buffer views
  #
  from_arraybuffer:(data)->
    if data instanceof ArrayBuffer
      @buffer_view = data
      @map_header()
      @pcm_buff = []
      chlen = @get_pcmbuff_len()
      chnum = @get_channel_count()
      for ch in [0...chnum]
        @pcm_buff.push(new Float32Array(@buffer_view, @HEADER_SIZE + chlen * ch * 4, chlen))
    else 
      console.log 'unknown data type'
    return

  get_uid:()->
    if @uid_buf?
      return @uid_buf[0]
    else
      return null

  get_sid:()->
    if @sid_buf?
      return @sid_buf[0]
    else
      return null

  get_pcmbuff_len:->
    if @len_buf?
      @len_buf[0]
    else
      return 0

  get_channel_count:->
    if @channel_buf?
      @channel_buf[0]
    else
      return 0
